﻿//////////////////////////////////////////////////////////////////////////
// route module
// author   : zhangpeng
// date     : 2012-2-6
//////////////////////////////////////////////////////////////////////////
var exec = require("child_process").exec;
var querystring = require("querystring");
var formidable = require('formidable'); 
var fs = require("fs");

function start(res, req) {
    console.log("request handler 'start' was called.");
    var content = "empty";
    exec("dir", { timeout: 3000, maxBuffer: 20000 * 1024 }, function(error, stdout, stderr) {
        content = stdout;
        res.writeHead(200, { "Content-Type": "text/plain" });
        res.write(content);
        res.end();
    });
}
function startPost(res, req) {
    console.log("request handler 'startPost' was called.");
    var body = "<html>" + 
    "<head>" +
    '<meta http-equiv="Content-Type" content="text/html; ' +
    'charset=UTF-8" />' +
    '</head>' +
    '<body>' +
    '<form action="/upload" method="post">' +
    '<textarea name="text" rows="20" cols="60"></textarea>' +
    '<input type="submit" value="Submit text" />' +
    '</form>' +
    '</body>' +
    '</html>';
    res.writeHead(200, { "Content-Type": "text/html" });
    res.write(body);
    res.end();
}
function index(res, req) {
    var body = '<html>' +
    '<head>' +
    '<meta http-equiv="Content-Type" ' +
    'content="text/html; charset=UTF-8" />' +
    '</head>' +
    '<body>' +
    '<form action="/upload" enctype="multipart/form-data" ' +
    'method="post">' +
    '<input type="file" name="upload">' +
    '<input type="submit" value="Upload file" />' +
    '</form>' +
    '</body>' +
    '</html>';
    res.writeHead(200, { "Content-Type": "text/html" });
    res.write(body);
    res.end();
}
var globalIndex = 0;
function upload(res, req) {
    console.log("request handler 'upload' was called.");
    var form = new formidable.IncomingForm();
    console.log("about to parse");
    form.parse(req, function(error, fields, files) {
        console.log("parsing done");
        fs.renameSync(files.upload.path, "E:\\node\\demo1\\tmp\\test"+ globalIndex +".png");
        res.writeHead(200, { "Content-Type": "text/html" });
        res.write("received image:<br/>");
        res.write("<img src='/show' />");
        res.end();
    });
}
function show(res, req) {
    fs.readFile("E:\\node\\demo1\\tmp\\test" + globalIndex + ".png", "binary", function(error, file) {
        if (error) {
            res.writeHead(500, { "Content-Type": "text/plain" });
            res.write(error + "\n");
            res.end();
        } else {
            res.writeHead(200, { "Content-Type": "image/png" });
            res.write(file, "binary");
            res.end();
        }
        globalIndex += 1;
    })
}
exports.start = start;
exports.upload = upload;
exports.startPost = startPost;
exports.show = show;
exports.index = index;